package Client;

import java.awt.event.*;

public class Controller {

	private View view;
	private NetworkClientTest clientTest;
	private final String SUCCESSFUL = "200 Successfully found";
	private final String UNSUCCESSFUL = "300 Name does not exist";

	public Controller(View view, NetworkClientTest clientTest) {
		this.view = view;
		this.clientTest = clientTest;
		view.addValueListener(new ValueListener());
	}

	class ValueListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			String userInput;
			try {
				userInput = view.getText(); // get input from textfield
				emptyTable(); // this is necessary because when button is
								// clicked more than once, table will show the
								// old rows.
				clientTest.setLogLineName(userInput);
				clientTest.connect();
				if (clientTest.getViewList().size() > 0) {
					for (int i = clientTest.getViewList().size() - 1; i >= 0; i--) {
						view.getTableModel().insertRow(
								0,
								new Object[] {
										clientTest.getViewList().get(i)
												.getName(),
										Integer.toString(clientTest
												.getViewList().get(i)
												.getValue()) });
					}
					view.setAreaText(SUCCESSFUL);
				} else {
					view.setAreaText(UNSUCCESSFUL);
				}

			} catch (NumberFormatException nfex) {
				nfex.getMessage();
			}
		}

		/* This method removes all rows of table. */
		private void emptyTable() {
			int numrows = view.getTable().getRowCount();
			for (int i = numrows - 1; i >= 0; i--) {
				view.getTableModel().removeRow(i);
			}
		}
	}
}
